<template>
	<a-drawer v-model:open="visible" ref="employeeDetailModalRef" class="edit-drawer modal-fixed-bottom"
		root-class-name="root-customer-drawer" width="800px" :closable="false" @close="onClose">
		<div class="closeable" @click="onClose">{{ $t('self.closeButton') }}</div>
		<div class="modal-header">{{ title }}</div>
		<a-form :model="formState" :rules="formRules" :label-col="labelCol" :wrapper-col="wrapperCol"
			@finish="onSubmit" ref="formRef">
			<a-form-item :label="$t('self.businessStation.modal.col3')" name="orgId">
				<a-select v-model:value="formState.orgId" :options="orgOptions"
					:fieldNames="{label: 'orgName',value: 'id'}" :placeholder="$t('self.pleaseChoose')"
					@change="getTariffPolicy" />
			</a-form-item>
			<a-form-item :label="$t('self.businessStation.tips1')" name="stationName">
				<a-input allow-clear v-model:value="formState.stationName" placeholder="" />
			</a-form-item>

			<a-form-item name="stationProvince" :label="$t('self.operators.tips46')" >
				<a-select allow-clear v-model:value="formState.stationProvince" 
				:options="africaCountryOptions"   :field-names="{ label: 'display', value: 'value' }"  @change="handleAfricaCountryChange"
				:placeholder="$t('self.pleaseChoose')">
				</a-select>
			</a-form-item>
			<a-form-item name="stationCity" :label="$t('self.operators.tips45')">
				<a-select allow-clear v-model:value="formState.stationCity" 
				:options="africaTestTypeOptions"
				:field-names="{ label: 'label', value: 'labelEn' }" @change="handleAfricaTestTypeChange"
				:placeholder="$t('self.pleaseChoose')">
				</a-select>
			</a-form-item>

			<a-form-item :label="$t('self.businessStation.modal.col5')" name="stationAreaDetail">
				<a-input allow-clear v-model:value="formState.stationAreaDetail" placeholder="" />
			</a-form-item>

			<a-form-item :label="$t('self.businessStation.tips3')" name="longitude">
				<a-input allow-clear v-model:value="formState.longitude" placeholder="" />
			</a-form-item>
			<a-form-item :label="$t('self.businessStation.tips4')" name="latitude">
				<a-input allow-clear v-model:value="formState.latitude" placeholder="" />
			</a-form-item>

			<a-form-item :label="$t('self.businessStation.tips16')" name="modelType">
				<a-select v-model:value="formState.modelType" :options="modelType" />
			</a-form-item>

			<a-form-item :label="$t('self.businessStation.modal.col14')" name="supportingFacilities">
				<a-select v-model:value="formState.supportingFacilities" :options="supportingFacilitiesOptions" />
			</a-form-item>

			<a-form-item :label="$t('self.businessStation.modal.col6')" name="tariffPolicy">
				<a-select v-model:value="formState.tariffPolicy" :options="tariffPolicyOptions"
					:fieldNames="{label: 'policyName',value: 'id'}" :placeholder="$t('self.pleaseChoose')" />
			</a-form-item>

			<a-form-item :label="$t('self.businessStation.modal.col7')" name="mobile">
				<a-input allow-clear v-model:value="formState.mobile" placeholder="" />
			</a-form-item>

			<a-form-item :label="$t('self.businessStation.modal.col8')" name="operatingStatus">
				<a-select v-model:value="formState.operatingStatus" :options="[
                    { label: $t('self.businessStation.statusType.tips1'), value: 0 },
                    { label: $t('self.businessStation.statusType.tips2'), value: 1 },
                    { label: $t('self.businessStation.statusType.tips3'), value: 2 },
					{ label: $t('self.businessStation.statusType.tips6'), value: 3 },
					{ label: $t('self.businessStation.statusType.tips7'), value: 4 },
                ]" />
			</a-form-item>

			<!--充电接口-->
			<a-form-item :label="$t('self.businessCharging.tips16')" name="chargeInterface">
				<a-select mode="multiple" v-model:value="formState.chargeInterface" :options="cdqjkOptions1"
					:fieldNames="{label: 'label',value: 'key'}" :placeholder="$t('self.pleaseChoose')" />
			</a-form-item>

			<a-form-item :label="$t('self.businessStation.modal.col13')" name="characteristic">
				<a-select mode="multiple" v-model:value="formState.characteristic" :options="cdqjkOptions"
					:fieldNames="{label: 'label',value: 'key'}" :placeholder="$t('self.pleaseChoose')" />
			</a-form-item>

			<div class="base-flex base-rows base-align-items-center base-justify-content-center footer">
				<a-button type="primary" html-type="submit">{{ $t('self.submitButton') }}</a-button>
				<a-button class="base-ml10" @click="onClose">{{ $t('self.cancelButton') }}</a-button>
			</div>
		</a-form>
	</a-drawer>
</template>

<script setup>
	import {
		computed,
		getCurrentInstance,
		onMounted,
		ref,
		watch
	} from 'vue'
	import {
		message
	} from 'ant-design-vue'
	import chooseAreaForLocal from '@/components/choose/choose-area-for-local.vue'
	import config from '@/config'
	const {
		proxy
	} = getCurrentInstance()
	const $TOOL = proxy.$TOOL
	const $API = proxy.$API
	const $T = proxy.$t
	import tool from '@/utils/tool'
	const emit = defineEmits(['close', 'ok'])

	// 添加表单引用
	const formRef = ref(null)

	import cityData from '@/config/data.js'
	import dayjs from 'dayjs'
	const countryAuthorizeOptions = ref([])
	const cityRaw = cityData.cityRaw

	const visible = ref(false)
	const token = tool.cookie.get(config.TOKEN_KEY);

	// 模式，add新增，show查看，edit编辑
	const mode = ref('add')
	const labelCol = {
		style: {
			width: '230px',
		},
	};
	const wrapperCol = {
		span: 16,
	};

	const title = ref('')
	const formState = ref({
		id: '',
		orgId: null,
		stationName: '',
		stationProvince: '',
		stationCity: '',
		stationArea: '',
		stationAreaDetail: '',
		longitude: '',
		latitude: '',
		tariffPolicy: null,
		mobile: '',
		operatingStatus: 0, // 0：待开通、1：维护中、2：运营中
		chargeInterface: [],
		characteristic: [],
		supportingFacilities: '',
		modelType: '',
		authorizedCountryCode: null,
	})
	const areaArr = ref([]) // 省市区的集合
	const orgOptions = ref([])
	const tariffPolicyOptions = ref([]) // 资费的下拉列表

	const cdqjkOptions = ref([{
			label: 'Rest room',
			key: 'Rest room'
		},
		{
			label: 'Parking facility',
			key: 'Parking facility'
		},
		{
			label: 'Power backup',
			key: 'Power backup'
		}
	])

	const supportingFacilitiesMap = {
		0: 'E-MOTOS',
		1: 'E-CARS',
	};

	const supportingFacilitiesReverseMap = {
		'E-MOTOS': 0,
		'E-CARS': 1,
	};

	const supportingFacilitiesOptions = [{
			label: 'E-MOTOS',
			value: 'E-MOTOS'
		},
		{
			label: 'E-CARS',
			value: 'E-CARS'
		},
	];
	const modelType = [{
			label: 'Flagship',
			value: 'Flagship'
		},
		{
			label: 'Pop-up',
			value: 'Pop-up'
		},
		{
			label: 'Parttnered',
			value: 'Parttnered'
		},
	];
	// 充电接口的下拉列表
	const cdqjkOptions1 = ref([{
			label: 'Type 2',
			key: 'Type 2'
		},
		{
			label: 'SAE J1772',
			key: 'SAE J1772'
		},
		{
			label: 'CHAdeMO',
			key: 'CHAdeMO'
		},
		{
			label: 'GB/T',
			key: 'GB/T'
		},
		{
			label: 'Tesla',
			key: 'Tesla'
		}
	])

	const formRules = ref({
		orgId: [{
			required: true,
			message: $T('self.pleaseChoose') + $T('self.businessStation.modal.col3'),
			trigger: 'change'
		}],
		stationName: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessStation.tips1'),
			trigger: 'change'
		}],
		// 删除了不存在的stationArea字段验证
		stationAreaDetail: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessStation.modal.col5'),
			trigger: 'change'
		}],
		longitude: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessStation.tips3'),
			trigger: 'change'
		}],
		latitude: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessStation.tips4'),
			trigger: 'change'
		}],
		tariffPolicy: [{
			required: true,
			message: $T('self.pleaseChoose') + $T('self.businessStation.modal.col6'),
			trigger: 'change'
		}],
		mobile: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessStation.modal.col7'),
			trigger: 'change'
		}],
		operatingStatus: [{
			required: true,
			message: $T('self.pleaseChoose') + $T('self.businessCharging.modal.col8'),
			trigger: 'change'
		}],
		supportingFacilities: [{
			required: true,
			message: $T('self.pleaseChoose') + $T('self.businessCharging.modal.col14'),
			trigger: 'change'
		}],
		chargeInterface: [{
			required: true,
			message: $T('self.pleaseChoose') + $T('self.businessCharging.tips16'),
			trigger: 'change'
		}],
		modelType: [{
			required: true,
			message: $T('self.pleaseChoose') + $T('self.businessStation.tips16'),
			trigger: 'change'
		}],
		stationProvince: [{
			required: true,
			message: $T('self.pleaseChoose') + $T('self.operators.tips46'),
			trigger: 'change'
		}],
		stationCity: [{
			required: true,
			message: $T('self.pleaseChoose') + $T('self.operators.tips45'),
			trigger: 'change'
		}],
	})

	const africaTestTypeOptions = computed(() => {
		const selectedCountry = formState.value.authorizedCountryCode;
		if (!selectedCountry) return [];

		const cities = cityRaw[selectedCountry] || [];
		return cities.map(c => ({
			label: `${c.labelCn} / ${c.labelEn}` + (c.labelRW ? ` / ${c.labelRW}` : ''),
			value: `${selectedCountry}_${c.labelEn}`,
			countryCode: selectedCountry,
			labelCn: c.labelCn,
			labelEn: c.labelEn, // 添加labelEn属性
			labelRW: c.labelRW
		}));
	});

	const handleAfricaCountryChange = async (countryCode) => {
		formState.value.authorizedCountryCode = countryCode;
		formState.value.stationCity = ''; // 清空城市选择
		const selectedCountry = africaCountryOptions.find(item => item.value === countryCode);
		formState.value.stationProvince = selectedCountry ? selectedCountry.labelEn : '';
	};

	const africaCountryOptions = cityData.africaCountryOptions.map(item => ({
		...item,
		display: `${item.labelCn} / ${item.labelEn}` + (item.labelRW ? ` / ${item.labelRW}` : '')
	}));

	const handleAfricaTestTypeChange = (testType) => {
		formState.value.africaTestType = testType;
		const selectedCity = africaTestTypeOptions.value.find(item => item.labelEn === testType);
		formState.value.stationCity = selectedCity ? selectedCity.labelEn : '';
	};

	// 监听stationProvince变化，自动设置authorizedCountryCode
	watch(() => formState.value.stationProvince, (newProvince) => {
		if (newProvince && mode.value === 'edit') {
			// 根据省份名称查找对应的countryCode
			const country = africaCountryOptions.find(item => item.labelEn === newProvince);
			if (country) {
				formState.value.authorizedCountryCode = country.value;
			}
		}
	}, { immediate: true });

	onMounted(async () => {
		orgOptions.value = await proxy.getOrgSelectList(true)
	})

	const getTariffPolicy = async () => {
		tariffPolicyOptions.value = await proxy.getTariffPolicySelectListByOrg(formState.value.orgId)
	}

	const handleChangeArea = (area) => {
		formState.value.stationProvince = area[0]
		formState.value.stationCity = area[1]
		formState.value.stationArea = area[2]
	}

	const onSubmit = async (values) => {
		try {
			const params = {
				...formState.value
			}

			if (Array.isArray(params.characteristic)) {
				params.characteristic = params.characteristic.filter(item => item).join(',');
			}

			if (Array.isArray(params.chargeInterface)) {
				params.chargeInterface = params.chargeInterface.filter(item => item).join(',');
			}

			params.supportingFacilities = formState.value.supportingFacilities;

			if (mode.value === 'add') {
				// 添加
				const res = await $API.backend.businessStation.add.post(params)
				message.success($T('self.message.success'))
				onReset()
				visible.value = false
				emit('ok')
			} else {
				// 修改
				const res = await $API.backend.businessStation.edit.post(params)
				message.success($T('self.message.success'))
				onReset()
				visible.value = false
				emit('ok')
			}
		} catch (err) {
			message.error(err.msg || $T('self.message.error'))
		}
	}

	const onReset = () => {
		// 清空内容
		areaArr.value = []
		tariffPolicyOptions.value = []
		formState.value = {
			id: '',
			orgId: null,
			stationName: '',
			stationProvince: '',
			stationCity: '',
			stationArea: '',
			stationAreaDetail: '',
			longitude: '',
			latitude: '',
			tariffPolicy: '',
			mobile: '',
			operatingStatus: 0,
			chargeInterface: [],
			characteristic: [], // 提供的服务
			supportingFacilities: '',
			modelType: '',
			authorizedCountryCode: null,
		}
		// 重置表单验证状态
		if (formRef.value) {
			formRef.value.resetFields()
		}
	}

	const onClose = () => {
		onReset()
		visible.value = false
		emit('close')
	}

	const add = () => {
		mode.value = 'add'
		title.value = $T('self.businessStation.modal.col1')
		visible.value = true
		onReset()
	}

	const edit = (record) => {
		mode.value = 'edit'
		// 克隆存在的键
		$TOOL.array.cloneExistKey(formState.value, record)

		// 解析 characteristic 字段
		if (record.characteristic) {
			formState.value.characteristic = record.characteristic.split(',').map(item => item.trim());
		} else {
			formState.value.characteristic = [];
		}

		// 解析 chargeInterface 字段
		if (record.chargeInterface) {
			formState.value.chargeInterface = record.chargeInterface.split(',').map(item => item.trim());
		} else {
			formState.value.chargeInterface = [];
		}

		// 将 supportingFacilities 数字转换为字符串
		if (typeof record.supportingFacilities === 'number') {
			formState.value.supportingFacilities = supportingFacilitiesMap[record.supportingFacilities];
		} else {
			formState.value.supportingFacilities = record.supportingFacilities;
		}

		// 将 operatingStatus 从字符串转换为数字
		formState.value.operatingStatus = parseInt(record.operatingStatus, 10);

		// 设置省份和城市
		formState.value.stationProvince = record.stationProvince || '';
		formState.value.stationCity = record.stationCity || '';
		
		// 根据省份名称查找对应的countryCode
		if (record.stationProvince) {
			const country = africaCountryOptions.find(item => item.labelEn === record.stationProvince);
			if (country) {
				formState.value.authorizedCountryCode = country.value;
			}
		}
		//formState.value.modelType = record.modelType || '';
		title.value = $T('self.businessStation.modal.col2') + '：' + formState.value.stationName
		visible.value = true

		if (formState.value.orgId) {
			getTariffPolicy()
		}
	}

	// 子组件中要通过defineExpose将方法暴露给父组件
	defineExpose({
		add,
		edit,
	})
</script>

<style lang="scss" scoped>
	.edit-drawer {
		position: relative;

		.closeable {
			@include closeable;
		}
	}

	.my-upload {
		::v-deep(.ant-upload) {
			width: 100px;
			height: 100px;
		}
	}

	.adv-list {
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
		margin-top: 10px;
	}

	.adv-item {
		width: 100px;
		text-align: center;
		padding-top: 5px;
		height: 100px;
		position: relative;
	}

	.pic-box img {
		width: 100px;
		height: 100px;
		object-fit: cover;
	}

	.del-box {
		position: absolute;
		right: 0px;
		top: 0px;
	}

	.del-box img {
		width: 20px;
		height: 20px;
		cursor: pointer;
		margin: 4px 0;
	}

	.upload-line {
		display: flex;
		align-items: center;
		gap: 12px;
	}

	.upload-tip {
		font-size: 12px;
		color: #999;

		.count {
			margin-left: 8px;
			color: #faad14;
		}
	}
</style>